﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
    public static class EnumerableExt
    {
        /// <summary>
        /// Determines whether the distionary
        ///     contains an element with the specified key. If key is null returns false
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TVal"></typeparam>
        /// <param name="source"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool ContainsKeySafe<TKey, TVal>(this IDictionary<TKey, TVal> source, TKey key)
        {
            if (key.IsNotNull())
                return source.ContainsKey(key);
            return false;
        }
        public static bool AddIfNotExist<TKey, TVal>(this IDictionary<TKey, TVal> source, TKey key, TVal value)
        {
            if (key != null && !source.ContainsKey(key))
            {
                source.Add(key, value);
                return true;
            }
            return false;
        }
        public static bool RemoveIfExist<TKey, TVal>(this IDictionary<TKey, TVal> source, TKey key)
        {
            if (key != null && source.ContainsKey(key))
            {
                source.Remove(key);
                return true;
            }
            return false;
        }
        public static bool AddIfNotExist<TKey>(this List<TKey> source, TKey value)
        {
            if (value != null && !source.Contains(value))
            {
                source.Add(value);
                return true;
            }
            return false;
        }
        public static bool RemoveIfExist<TKey>(this List<TKey> source, TKey value)
        {
            if (value != null && source.Contains(value))
            {
                source.Remove(value);
                return true;
            }
            return false;
        }
    }
}
